/**
 * Created by tdzl2003 on 8/24/16.
 */

import React, {PropTypes} from 'react';
import { Table, Pagination, Alert } from 'antd';
import '../utils/asyncSetState';
import filterObject from 'fbjs/lib/filterObject';

export default class ObjectTable extends React.Component{
  static propTypes = {
    ...Table.propTypes,

    columns: PropTypes.array,
    initialPagination: PropTypes.shape({
      ...Pagination.propTypes,
    }),
    fetchData: PropTypes.func.isRequired,
  };

  static defaultProps = {
    ...Table.defaultProps,

    initialPagination: {
      current: 1,
      pageSize: 20,
      showSizeChanger: true,
      showTotal: total=> `共${total}个对象`,
      showQuickJumper: true,
    },
  };

  state = {
    data: [],
    error: null,
    pagination: this.props.initialPagination,
    loading: false,
    sorter: {},
    filters: [],
  };

  handleTableChange = async (pagination, filters, sorter) => {
    console.log(filters);
    const pager = {
      ...this.state.pagination,
      pageSize: pagination.pageSize,
      current: pagination.current,
    };
    await this.setState({
      pagination: pager,
      sorter: sorter,
      filters: filters,
    });
    this.fetch({
      pageSize: pagination.pageSize,
      page: pagination.current - 1,
      sortField: sorter.field,
      sortOrder: sorter.order,
      ...filters,
    });
  };
  refresh() {
    const {pagination, sorter, filters} = this.state;

    this.fetch({
      pageSize: pagination.pageSize,
      page: pagination.current - 1,
      sortField: sorter.field,
      sortOrder: sorter.order,
      ...filters,
    });
  }
  async fetch(params = {}) {
    const {fetchData} = this.props;

    try {
      this.setState({
        loading: params,
      });
      // 发起请求,同时获得当前页和总数
      const {data, count} = await fetchData(params);
      const pagination = this.state.pagination;
      if (params !== this.state.loading) {
        // 避免多个请求同时发出导致的返回数据不是当前页或者不符合当前排序、过滤器的问题。
        return;
      }
      if (__DEV__){
        console.log("后台返回的数据",data);
      }

      this.setState({
        loading: false,
        error: false,
        data: data,
        pagination: {
          ...pagination,
          total: count,
        },
      });
    } catch (err) {
      this.setState({
        loading: false,
        error: err.message,
      })
    }
  }

  componentDidMount() {
    const {pagination} = this.state;
    this.fetch({
      pageSize: pagination.pageSize,
      page: pagination.current - 1,
    });
  }
  renderFooter = () => {
    const {error} = this.state;
    if (error) {
      return (
        <Alert message={error} type="error" />
      )
    }
    return null;
  }
  removeItem(item){
    this.setState({
      data: this.state.data.filter(v=>v!==item),
    });
  }
  render() {
    const tableProps = filterObject(this.props, (v,k)=>Table.propTypes[k] || k==='title' ||k==='expandedRowRender');

    return (
      <Table
        {...tableProps}
        columns={this.props.columns}
        rowKey={record => record.id}
        dataSource={this.state.data}
        pagination={this.state.pagination}
        loading={!!this.state.loading}
        onChange={this.handleTableChange}
        footer={this.renderFooter}
      />
    );
  }
}
